# coding=utf-8
import redis
from django.conf import settings


HOST = settings.REDIS['default']['HOST']
PORT = settings.REDIS['default']['PORT']
PASSWORD = settings.REDIS['default']['PASSWORD']
DB = 0


class Singleton(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(
                Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]


class RedisSingleton(metaclass=Singleton):

    def __init__(self):
        self.redis = redis.Redis(
            host=HOST, port=PORT, db=DB, password=PASSWORD,
            decode_responses=True)


class LoginCaptcha(object):

    """
    用于记录登录ID对应的验证码文本
    """

    key_prefix = "login_captcha_{0}"

    def __init__(self):
        self.redis = RedisSingleton().redis

    def set(self, login_id, captcha_text):
        key = self.key_prefix.format(login_id)
        expire = settings.LOGIN_EXPIRE_SECONDS
        self.redis.set(key, captcha_text, ex=expire)

    def get(self, login_id):
        key = self.key_prefix.format(login_id)
        return self.redis.get(key)

    def delete(self, login_id):
        key = self.key_prefix.format(login_id)
        return self.redis.delete(key)
